package com.boarsoft.boar.code.scaner.action;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.boarsoft.boar.config.service.ConfigVarService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.boarsoft.bean.ReplyInfo;
import com.boarsoft.boar.code.agent.service.CodeService;
import com.boarsoft.boar.code.agent.service.ScmService;
import com.boarsoft.boar.context.ActionContext;
import com.boarsoft.common.Util;
import com.boarsoft.rpc.core.RpcContext;

@RestController
@RequestMapping("/scan")
public class ScanAction {
	private static final Logger log = LoggerFactory.getLogger(ScanAction.class);
	@Resource
	@Qualifier("developerCodeService")
	private CodeService developerCodeService;

	@Resource
	@Qualifier("deployCodeService")
	private CodeService deployCodeService;

	@Resource
	@Qualifier("configVarSvc")
	private ConfigVarService configVarService;
	@Resource
	private ScmService scmService;

	@RequestMapping("/server.do")
	public ReplyInfo<Object> server(@RequestParam String path, String url, String branch) {
		try {
			if (Util.strIsNotEmpty(url) && Util.strIsNotEmpty(branch)) {
				String rs = scmService.pull(url, branch);
				log.info("Pull source code from branch {} of {}, result: {}", branch, url, rs);
			}
			deployCodeService.scan(path);
			return ReplyInfo.SUCCESS;
		} catch (IOException e) {
			log.error("Error on scan code by deploy agent", e);
			return new ReplyInfo<>(e.getMessage());
		}
	}

	@RequestMapping("/local.do")
	public ReplyInfo<Object> local(@RequestParam String path, HttpServletRequest request) {
		String ip = ActionContext.getRemoteIp(request);
		if (Util.strIsEmpty(ip)) {
			return new ReplyInfo<Object>("Can not get your IP address");
		}
		RpcContext.specify2(ip.concat(":9941"));
		try {
			developerCodeService.scan(path);
		} catch (IOException e) {
			log.error("Error on scan code by developer code agent", e);
		} finally {
			RpcContext.specify2(null);
		}
		return ReplyInfo.SUCCESS;
	}
}
